﻿using System;
using UnityEditor;
using UnityEngine;

namespace ChangeSkin
{
    [ToolButton("Hierarchy对象", "所有子对象新建父对象")]
    public class NewChildsRoot:IToolsButtonEvent
    {
        public void Run()
        {
            if (Selection.activeGameObject == null)
            {
                Debug.LogError("没有选择对象");
                return;
            }
            foreach(var item in Selection.gameObjects)
            {
                 CreateChildParent(item.transform);
            }


        }
        Transform CreateChildParent(Transform transform)
        {
            var count = transform.childCount;
            if (count == 0)
                return null;

            var parent = new GameObject("newParent").transform;
            var childs = new Transform[count];

            for (var i = 0; i < count; i++)
            {
                childs[i] = transform.GetChild(i);
            }
            foreach (var child in childs)
            {
                child.SetParent(parent, false);
            }

            parent.SetParent(transform);

            return parent;
        }
    }

}